package com.graduation.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.model.R;
import com.graduation.ucenter.feignclient.CheckCodeClient;
import com.graduation.ucenter.mapper.UserMapper;
import com.graduation.ucenter.model.dto.RegisterDto;
import com.graduation.ucenter.model.dto.UserDto;
import com.graduation.ucenter.model.po.Role;
import com.graduation.ucenter.model.po.User;
import com.graduation.ucenter.service.RoleService;
import com.graduation.ucenter.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 小何
 * @Description: TODO
 * @DateTime: 2023/10/30 10:27
 **/
@Service
public class UserManageServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private CheckCodeClient checkCodeClient;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleService roleService;

    @Override
    @Transactional
    public R<String> register(User user) {
        //1.向User表中添加User信息
        userService.save(user);
        //2.向用户角色表添加信息,普通注册用户角色为普通用户
        userMapper.addRoleUser(user.getId(), 1);
        return R.success("注册成功");
    }

    @Override
    public R<List<User>> listUser(Integer page, Integer pageSize, User user) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        if (user != null) {
            qw.like(user.getUsername() != null && !"".equals(user.getUsername()), User::getUsername, user.getUsername())
                    .eq(user.getEmail() != null && !"".equals(user.getEmail()), User::getEmail, user.getEmail())
                    .eq(user.getId() != null, User::getId, user.getId());
        }
        Page<User> userPage = new Page<>(page, pageSize);
        this.page(userPage, qw);
        Map<String, Object> map = new HashMap<>();
        map.put("count", userPage.getTotal());
        return R.success(userPage.getRecords(), map);
    }

    @Override
    public R<String> disableUser(Integer userId) {
        updateUserStatus(userId, 0);
        return R.success("禁用成功");
    }

    @Override
    public R<String> enableUser(Integer userId) {
        updateUserStatus(userId, 1);
        return R.success("启用成功");
    }

    @Override
    public R<String> addBindRoleByUserId(Integer roleId, Integer userId) {
        int i = userMapper.judgeRoleUserContains(userId, roleId);
        if (i != 0) {
            return R.error("已绑定该角色");
        }
        userMapper.addRoleUser(userId, roleId);
        return R.success("绑定成功");
    }

    @Override
    public R<String> removeBindRoleByUserId(Integer roleId, Integer userId) {
        userMapper.removeRoleUser(userId, roleId);
        return R.success("取消绑定成功");
    }

    @Override
    public R<String> addUser(User user) {
        //1.判断用户是否已存在
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(user != null && user.getUsername() != null && !"".equals(user.getUsername()), User::getUsername, user.getUsername());
        User one = this.getOne(qw);
        if (one != null) {
            return R.error("用户已存在");
        }
        user.setRegisterdate(new Timestamp(System.currentTimeMillis()));
        user.setStatus(1);
        this.save(user);
        return R.success("用户添加成功");
    }

    @Override
    @Transactional
    public R<String> commonRegister(RegisterDto registerDto) {
        Boolean verify = checkCodeClient.verify(registerDto.getCheckKey(), registerDto.getCheckCode());
        if (!verify) {
            return R.error("验证码错误");
        }
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUsername, registerDto.getUsername());
        User one = userService.getOne(qw);
        if (one != null) {
            return R.error("用户名已存在");
        }
        User user = new User();
        BeanUtils.copyProperties(registerDto, user);
        PasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        user.setStatus(1);
        userService.save(user);
        userMapper.addUserRole(user.getId());
        return R.success("注册成功,请登录");
    }

    private void updateUserStatus(Integer userId, Integer status) {
        UpdateWrapper<User> uw = new UpdateWrapper<>();
        uw.eq("Id", userId)
                .set("status", status);
        this.update(uw);
    }
}
